<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="设备类型">
          <el-select
            v-model="searchParam.equipTypeId"
            placeholder="请选择设备类型"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in equipTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-input
            v-model="searchParam.locationId"
            placeholder="请输入位置"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input
            v-model="searchParam.equipCode"
            placeholder="请输入设备编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="searchParam.equipName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button type="success" @click="excelBoxOpen">导入 </el-button>
        <el-dialog
          :close-on-click-modal="false"
          title="设备信息数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/iotadmin/scaequipinfo/exportTemp',
                  '设备信息上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              设备信息上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="设备编号"
          prop="equipCode"
          min-width="180"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="设备名称"
          prop="equipName"
          min-width="180"
          show-overflow-tooltip
          sortable
        />
        <el-table-column
          label="设备类型"
          prop="equipTypeName"
          min-width="180"
          align="center"
          show-overflow-tooltip
          sortable
        >
          <template #default="scope">
            {{ scope.row.equipTypeCode }}
          </template>
        </el-table-column>
        <el-table-column
          label="生产设备"
          prop="processEquipCode"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="IP地址"
          prop="ipAddress"
          min-width="180"
          show-overflow-tooltip
        />

        <el-table-column
          label="位置"
          prop="locationId"
          min-width="180"
          show-overflow-tooltip
          align="center"
          sortable
        >
          <template #default="scope">
            {{ scope.row.locationName }}
          </template>
        </el-table-column>
        <el-table-column
          label="是否启用"
          prop="enabled"
          min-width="120"
          align="center"
          sortable
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="450" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="scaequipinfoCopy(scope.row.id)"
            >
              <i-ep-switch />设备复制</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openCollectParameters(scope.row)"
            >
              <i-ep-dataAnalysis />采集参数</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openControlParameters(scope.row)"
            >
              <i-ep-connection />控制参数</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="openAlarmSettings(scope.row)"
              ><i-ep-setting /> 报警设置</el-button
            >
            <el-dropdown
              size="small"
              @click="handleClick"
              style="margin-left: 10px"
            >
              <el-button type="primary" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openDialogdetail(scope.row)"
                    >查看</el-dropdown-item
                  >
                  <el-dropdown-item @click="openDialog(scope.row)"
                    >编辑</el-dropdown-item
                  >
                  <!-- <el-dropdown-item @click="openCollectParameters(scope.row)"
                    >采集参数</el-dropdown-item
                  >
                  <el-dropdown-item @click="openControlParameters(scope.row)"
                    >控制参数</el-dropdown-item
                  > -->
                  <el-dropdown-item
                    @click="openClearSettingParameters(scope.row)"
                    >清洗设置</el-dropdown-item
                  >
                  <!-- <el-dropdown-item @click="openAlarmSettings(scope.row)"
                    >报警设置</el-dropdown-item
                  > -->
                  <!-- <el-dropdown-item @click="scaequipinfoCopy(scope.row.id)"
                    >设备复制</el-dropdown-item
                  > -->
                  <el-dropdown-item @click="deleteItem(scope.row.id)"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <scaequipinfoContent-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <scaequipinfoClearSetting-edit
      :visible="addDialog1.visible"
      :title="addDialog1.title"
      :data="addDialog1.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : getTableList())"
      :is-readonly="addDialog1.readvisible"
      @change-visible1="changeVisible1"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useRouter } from "vue-router";
import { ArrowDown } from "@element-plus/icons-vue";
defineOptions({
  name: "IOTSCAEQUIPINFOCONTENT",
  inheritAttrs: false,
});
let router = useRouter();
// 请求参数
const requestApi = "/iotadmin/scaequipinfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  equipCode: "",
  equipName: "",
  equipTypeId: "",
  locationId: "",
};

const deleteParam = {
  api: "/iotadmin/scaequipinfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/iotadmin/scaequipinfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

// 导入excel
const uploadApi = "/iotadmin/scaequipinfo/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");
function excelBoxOpen() {
  excelBox.value = true;
}
function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

/** 打开设备信息表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改设备信息";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增设备信息";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

const handleClick = () => {
  console.log(11);
};

/** 打开设备信息表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "设备信息详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 清洗设置
const addDialog1 = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo1(id: string) {
  request({
    url: `/iotadmin/scaequipinfo/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog1.data = data.data;
      addDialog1.visible = true;
      console.log(addDialog1.data);
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开设备信息表单弹窗 */
function openClearSettingParameters(roleObj?: Object) {
  if (roleObj) {
    addDialog1.title = "清洗设置";
    addDialog1.visible = true;
    getInfo1(roleObj?.id);
  }
  addDialog1.readvisible = false;
}

function changeVisible1(value: boolean) {
  addDialog1.visible = value;
  if (!value) {
    addDialog1.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/iotadmin/scaequipinfo/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
    equipTypeList.value?.map((item: any) => {
      item.label = item.equipTypeName;
      item.value = item.id;
    });
  }
};

// 点击采集参数
const openCollectParameters = (row) => {
  router.push({
    path: "/iot/scaequipinfo/collectParameters",
    query: {
      id: row.id,
    },
  });
};
// 点击控制参数
const openControlParameters = (row: any) => {
  router.push({
    path: "/iot/scaequipinfo/controlParameters",
    query: {
      id: row.id,
    },
  });
};
// 点击报警设置
const openAlarmSettings = (row: any) => {
  router.push({
    path: "/iot/scaequipinfo/alarmSettings",
    query: {
      id: row.id,
    },
  });
};
// 查询详情
async function scaequipinfoCopy(id: string) {
  ElMessageBox.confirm("确认复制该条数据?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/iotadmin/scaequipinfo/copy/${id}`,
      method: "get",
    }).then((res) => {
      ElMessage.success("复制成功！");
      getTableList();
    });
  });
}
onMounted(() => {
  getEquipTypeList();
  getTableList();
});
</script>
<style lang="scss" scoped></style>
